package felix.rule.js.script;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import felix.rule.js.util.ListeningExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.script.ScriptException;
import java.util.UUID;
import java.util.concurrent.Executors;

@Service
@ConditionalOnProperty(prefix = "js", value = "enable", havingValue = "false", matchIfMissing = true)
@Slf4j
public class DisabledJsInvokeServiceImpl implements JsInvokeService {
    @Override
    public ListenableFuture<UUID> eval(String scriptBody) {
        return Futures.immediateFuture(UUID.randomUUID());
    }

    @Override
    public ListenableFuture<Object> invokeFunction(UUID scriptId, Object... args) {
        return Futures.immediateFailedFuture(new ScriptException("js engine is disabled,set JS_ENGINE_ENABLE=true to enable"));
    }

    @Override
    public ListenableFuture<Void> release(UUID scriptId) {
        return Futures.immediateFailedFuture(new ScriptException("js engine is disabled,set JS_ENGINE_ENABLE=true to enable"));
    }

    @Override
    public ListeningExecutor getJsExecutor() {
        JsExecutorServiceImpl jsExecutorService = new JsExecutorServiceImpl();
        jsExecutorService.setService(MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor()));
        return jsExecutorService;
    }
}
